package com.lmmob.autotest.uitest.controls;

import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.util.List;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class Combobox extends Control implements ValueSettable {
    private String label;

    private String id;

    public Combobox(String label, WebDriver webDriver) {
        super(webDriver);
        this.label = label;
    }

    @Override
    protected String getSelfQuery() {
        return String.format(".query(\"[fieldLabel='%s']\")[0]", this.label);
    }

    @Override
    protected String getName() {
        return this.label;
    }

    public void setValue(String value) {
        expand();
        List<WebElement> li = getBoundList();
        for (WebElement webElement : li) {
            if (webElement.getText().equals(value)) {
                webElement.click();
            }
        }
    }

    private List<WebElement> getBoundList() {
        String pickerId = (String) runScript(String.format("return Ext.ComponentQuery.query(\"[id='%s']\")[0].picker.id", getId()));
        return findElement(By.id(pickerId)).findElements(By.tagName("li"));
    }

    @Override
    public String getId() {
        if (StringUtils.isNotBlank(id))
            return id;
        try {
            id = (String) runScript("return " + this.getQuery() + ".id");
        } catch (Exception e) {
            Long len = (Long) runScript("return " + getParent().getQuery() + ".query(\"combobox\").length");
            for (int i = 0; i < len; ++i) {
                String fieldLabel = (String) runScript("return " + getParent().getQuery() + String.format(".query(\"combobox\")[%s].fieldLabel", i));
                if (StringUtils.isNotBlank(fieldLabel) && fieldLabel.contains(this.label)) {
                    id = (String) runScript("return " + getParent().getQuery() + String.format(".query(\"combobox\")[%s].id", i));
                }
            }
        }
        return id;
    }

    private void expand() {
        runScript(String.format("Ext.ComponentQuery.query(\"[id='%s']\")[0].expand();", getId()));
    }

    public void verifyValue(String expected) {
        WebElement container = findElement(By.id(getId()));
        assertThat(String.format("Combobox[label='%s']", this.label), getActualValue(container).trim(), is(expected));
    }

    private String getActualValue(WebElement container) {
        List<WebElement> elements = container.findElements(By.tagName("input"));
        for (WebElement element : elements) {
            if (element != null && !"hidden".equals(element.getAttribute("type"))) {
                return element.getAttribute("value");
            }
        }
        return StringUtils.EMPTY;
    }

    public void setId_dont_use_this(String id) {
        this.id = id;
    }
}
